﻿using Newtonsoft.Json;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace RM.BasicLibrary.Serializes
{
    public interface ISerialize
    {
        T Deserialize<T>(string json);
        string Serialize(object dynamic);
    }
    public class DataContractJson : ISerialize
    {
        public T Deserialize<T>(string json)
        {
            DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(T));
            MemoryStream ms_new = new MemoryStream(Encoding.Default.GetBytes(json));
            return (T)js.ReadObject(ms_new);
        }

        public string Serialize(object dynamic)
        {
            DataContractJsonSerializer js = new DataContractJsonSerializer(dynamic.GetType());
            MemoryStream ms = new MemoryStream();
            js.WriteObject(ms, dynamic);
            ms.Position = 0;
            return Encoding.Default.GetString(ms.ToArray());
        }
    }
    /// <summary>
    /// Newtonsoft
    /// </summary>
    public class NewtonsoftJson : ISerialize
    {
        public T Deserialize<T>(string json)
        {
            return JsonConvert.DeserializeObject<T>(json);
        }
        public string Serialize(object dynamic)
        {
            return JsonConvert.SerializeObject(dynamic);
        }
    }
    /// <summary>
    /// XmlSerializer
    /// </summary>
    public class XML : ISerialize
    {
        public T Deserialize<T>(string xml)
        {
            using (var str = new StringReader(xml))
            {
                var xmlSerializer = new XmlSerializer(typeof(T));
                var result = (T)xmlSerializer.Deserialize(str);
                return result;
            }
        }

        public string Serialize(object dynamic)
        {
            var emptyNamepsaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
            var serializer = new XmlSerializer(dynamic.GetType());
            var settings = new XmlWriterSettings();
            settings.OmitXmlDeclaration = true;
            settings.Encoding = Encoding.UTF8;
            using (var stream = new StringWriter())
            using (var writer = XmlWriter.Create(stream, settings))
            {
                serializer.Serialize(writer, dynamic, emptyNamepsaces);
                return stream.ToString();
            }
        }
    }
}
